<template>
    <div>
        <!-- 主内容区域 -->
        <div v-show="activeStatu">
            <el-card class="box">
                <div class="box-padding">
                    <!-- 搜索区域标题 -->
                    <div class="flex">
                        <div class="search-title">用户名称</div>
                        <div class="time_top">商品名称</div>
                        <div class="time-title">创建时间</div>
                    </div>
                    
                    <!-- 搜索框和筛选条件 -->
                    <div class="flexBox">
                        <!-- 用户名称搜索 -->
                        <div> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        
                        <!-- 商品名称搜索 -->
                        <div> 
                            <el-input v-model.trim="inputeds" @input="filterss" placeholder="输入内容"
                                class="search-input search-input-margin">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        
                        <!-- 日期范围选择 -->
                        <div class="date-picker-container">
                            <el-date-picker class="date-picker" @change="data_filters" v-model="time" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    
                    <!-- 操作按钮区域 -->
                    <div class="button-group">
                        <el-badge>
                            <el-button type="primary" @click="add" class="export-button">
                                导出
                            </el-button>
                        </el-badge>
                        
                        <!-- 状态筛选按钮 -->
                        <div class="status-buttons">
                            <el-badge :value="asl">
                                <el-button class="status-button" @click="asls" :type="whole">全部</el-button>
                            </el-badge>
                            <el-badge :value="bsl">
                                <el-button class="status-button" @click="aslss(1)" :type="lefts">待兑换</el-button>
                            </el-badge>
                            <el-badge :value="csl">
                                <el-button class="status-button" @click="aslss(2)" :type="rights">已兑换</el-button>
                            </el-badge>
                        </div>
                    </div>
                    
                    <!-- 数据表格 -->
                    <div> 
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                                class="data-table" :header-cell-style="{ 'text-align': 'center' }"
                                height="285">
                            <el-table-column type="selection" width="45" fixed="left" />
                            <el-table-column prop="id" label="id" width="150" fixed="left" align="center" />
                            <el-table-column prop="name" label="用户名称" width="150" align="center" />
                            <el-table-column prop="title" label="商品名称" show-overflow-tooltip width="190"
                                align="center" />
                            <el-table-column prop="num" label="总数量" width="150" align="center" />
                            <el-table-column prop="price" sortable label="总价格" width="150" align="center" />
                            
                            <!-- 状态列 -->
                            <el-table-column prop="address" label="状态" align="center" >
                                <template #default="scope">
                                    <div v-if="scope.row.status == 2 ? false : true" class="status-pending">
                                        未兑换</div>
                                    <div v-if="scope.row.status == 1 ? false : true" class="status-completed">已兑换</div>
                                </template>
                            </el-table-column>
                            
                            <el-table-column prop="createtime" label="购买时间" min-width="190" align="center" />
                            
                            <!-- 操作列 -->
                            <el-table-column label="操作" width="150" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div v-if="scope.row.status == 1 ? false : true" class="action-approved">已审核
                                        </div>
                                        <div v-if="scope.row.status == 2 ? false : true"
                                            class="action-pending"
                                            @click="shen(scope.row)">审核</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    
                    <!-- 分页控件 -->
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>

                    <!-- 删除确认对话框 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-message">确认删除该数据吗?</div>
                        <div class="dialog-buttons">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                    
                    <!-- 审核通过确认对话框 -->
                    <el-dialog v-model="shows" title="审核通过" center width="20vw">
                        <el-button @click="shows = false">取 消</el-button>
                        <el-button type="primary" @click="oks">确 定</el-button>
                    </el-dialog>
                    
                    <!-- 批量删除确认对话框 -->
                    <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                        <div class="dialog-message">确认删除这批数据吗?</div>
                        <span slot="footer" class="dialog-footer">
                            <div></div>
                            <div>
                                <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                                <el-button type="primary" @click="deleteid_t">确 定</el-button>
                            </div>
                        </span>
                    </el-dialog>
                </div>
            </el-card>
        </div>

        <!-- 新增/编辑分类表单 (当前未使用) -->
        <div v-show="activeStatud" class="form-container">
            <el-card class="form-card">
                <div class="form-title">{{ addText }}</div>
                <div class="divider"></div>
                <div class="form-content">
                  <el-form ref="ruleFormRef" class="form-width demo-ruleForm" :model="ruleForm" 
    status-icon :rules="rules" label-position="left" label-width="auto">
                        <el-form-item label="分类名称" prop="title" class="full-width">
                            <el-input v-model.trim="ruleForm.title" placeholder="请输入" class="full-width" />
                        </el-form-item>
                    </el-form>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { scoreChangeSta } from '../../../api/shopSwiper/index';
import { ElMessage, ElCard, ElDropdown } from 'element-plus';
import { Plus, Search, ArrowLeft, ArrowDown, RefreshRight } from '@element-plus/icons-vue';
import { scenicUpload } from '../../../api/uploading/index';
import { useRoute, useRouter } from 'vue-router';
import { Data, DataHistory } from '../../../api/home/home';
import * as XLSX from 'xlsx';
import table2excel from 'js-table2excel'

// 数据筛选和状态管理
const time = ref('')
const asl = ref('0') // 全部数量
const bsl = ref('0') // 待兑换数量
const csl = ref('0') // 已兑换数量

// 数据列表和视图状态
const activeList = ref([]); // 当前显示的数据
const activeStatu = ref(true) // 主视图显示状态
const activeStatud = ref(false) // 表单视图显示状态
const names = ref('导出');

// 注入外部函数和变量
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()
const testName = inject('testName')

const dialogTableVisible = ref(false);
const statused = ref('1'); // 状态标识(1:新增,2:编辑)
const router = useRouter();

// 表格分页控制
const inputed = ref(''); // 用户名称搜索关键词
const inputeds = ref(''); // 商品名称搜索关键词
const pageSize = ref(5);
const currentPage = ref(1);
const pageSizes = ref(5);
const currentPages = ref(1);
const copyList = ref([]); // 原始数据备份
const files = ref(false);
const synopsiss = ref('请输入简介')

// 当前操作的ID
const activId = ref('')
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);

const nm = ref([]) // 已兑换数据
const nn = ref([]) // 待兑换数据

// 初始化加载数据
render();
function render() {
    let bbb = [] // 临时存储待兑换数据
    let ccc = [] // 临时存储已兑换数据
    
    // 获取历史数据
    DataHistory().then((res) => {
        console.log(res);
        
        // 统计总数
        asl.value = res.data.length;
        
        // 分类统计待兑换和已兑换数据
        for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].status == '1') {
                bbb.push(res.data[i])
                bsl.value = bbb.length
                nn.value = bbb
            }
            else {
                ccc.push(res.data[i])
                csl.value = ccc.length
                nm.value = ccc
            }
        }
        
        // 更新数据列表
        activeList.value = res.data;
        copyList.value = res.data;
    });
}

// 表单数据
const ruleForms = reactive({
    name: ''
})

const list = ref([])
const lists = ref([])

// 获取当前时间字符串(用于导出文件名)
function getCurrentDateTimeString() {
    const now = new Date();
    const year = now.getFullYear().toString().slice();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart('0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    
    const dateTimeString = `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`;
    g = `${year}-${month}-${day}`
    return dateTimeString;
}

// 导出数据
function add() {
    if (activeList.value.length > 0) {
        // 定义导出的列配置
        const column = [
            {
                title: "序号",
                key: "id",
                type: "text",
            },
            {
                title: "用户名称",
                key: "name",
                type: "text",
            },
            {
                title: "商品名称",
                key: "title",
                type: "text",
            },
            {
                title: "数量",
                key: "num",
                type: 'text',
            },
            {
                title: "价格",
                key: "price",
                type: 'text',
            },
            {
                title: "购买时间",
                key: "createtime",
                type: "text",
            }
        ];
        
        // 导出数据
        getCurrentDateTimeString()
        let tableDatas = JSON.parse(JSON.stringify(activeList.value));
        let datas = tableDatas;
        table2excel(column, datas, "兑换记录" + g); // 导出文件名
    }
    else {
        ElMessage.error('暂无数据无法导出');
    }
}

// 表单数据和验证规则
const ruleForm = reactive({
    title: '',
});
const ruleFormRef = ref('');
const rules = reactive({
    title: [
        {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur',
        },
    ]
});

// 表单验证函数(未使用)
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

const imgUrls = ref('');

// 表单提交处理
const submitForm = (formEl) => {
    console.log(ruleForm);
    if (!formEl) return;
    
    formEl.validate((valid) => {
        if (valid) {
            if (statused.value == '1') {
                // 新增操作
                ruleForm.img = imgUrls.value;
                console.log(ruleForm);
                typeSave(ruleForm).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        render();
                    }
                });
            } else if (statused.value == '2') {
                // 编辑操作
                ruleForm.id = ids.value
                typeSave(ruleForm).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        render();
                    } else {
                        ElMessage({
                            message: '编辑失败，不能和原数据一致',
                            type: 'warning',
                        });
                    }
                });
            }
        }
        else {
            ElMessage({
                message: '新增失败',
                type: 'error',
            });
        }
    });
};

// 状态筛选按钮样式控制
const whole = ref('primary')
const lefts = ref('')
const rights = ref('')

// 筛选全部数据
function asls() {
    currentPage.value = 1
    whole.value = 'primary'
    lefts.value = ''
    rights.value = ''
    activeList.value = copyList.value
}

// 按状态筛选数据
function aslss(i) {
    if (i == '1') {
        // 筛选待兑换
        whole.value = ''
        lefts.value = 'primary'
        rights.value = ''
    }
    else if (i == '2') {
        // 筛选已兑换
        whole.value = ''
        lefts.value = ''
        rights.value = 'primary'
    }

    currentPage.value = 1
    
    // 根据状态筛选数据
    if (df.value != null) {
        df.value = dfs.value.filter(function (item) {
            if (String(item.status).indexOf(String(i)) > -1) {
                return df.value
            }
        })
        activeList.value = df.value
    }
    else if (df.value == null) {
        let a = [];
        activeList.value = copyList.value.filter(function (item) {
            if (String(item.status).indexOf(String(i)) > -1) {
                return activeList.value;
            }
        });
    }
}

// 审核操作
const shenId = ref('')
const shen = (e) => {
    console.log(e);
    shenId.value = e.id
    shows.value = true
}

// 确认审核
const oks = () => {
    scoreChangeSta({ id: shenId.value }).then(res => {
        if (res.code == '1') {
            ElMessage({
                message: '操作成功',
                type: 'success',
            });
            setTimeout(() => {
                shows.value = false;
            }, 1200);
            render();
        } else {
            ElMessage({
                message: '操作失败',
                type: 'error',
            });
        }
    })
}

// 编辑操作(当前未使用)
const ids = ref('');
const disableds = ref(true);

// 关闭表单
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
};

// 删除操作
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}

// 确认删除
const deleteids = ref('');
const centerDialogVisible = ref(false);
function deleteid() {
    typeDel({
        ids: deleteids.value,
    }).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}

// 搜索和筛选相关
const df = ref(null)
const dfs = ref(null)

// 用户名称搜索
function filters() {
    let hhh = [] // 临时存储待兑换数据
    let lll = [] // 临时存储已兑换数据
    
    currentPage.value = 1
    console.log(inputed.value);
    
    // 根据用户名称筛选
    activeList.value = copyList.value.filter(function (item) {
        if (String(item.name).indexOf(String(inputed.value)) > -1) {
            return activeList.value;
        }
    });
    
    // 更新筛选后的数据
    df.value = activeList.value
    dfs.value = activeList.value
    asl.value = activeList.value.length
    
    // 重新统计状态数量
    if (activeList.value != []) {
        asl.value = activeList.value.length
        bsl.value = 0
        csl.value = 0
    }
    
    // 分类统计待兑换和已兑换数据
    for (let i = 0; i < activeList.value.length; i++) {
        if (activeList.value[i].status == '1') {
            hhh.push(activeList.value[i])
            bsl.value = hhh.length
        }
        else {
            lll.push(activeList.value[i])
            csl.value = lll.length
        }
    }
    
    currentPage.value = 1
}

// 商品名称搜索
function filterss() {
    currentPage.value = 1
    console.log(inputeds.value);
    
    // 根据商品名称筛选
    activeList.value = copyList.value.filter(function (item) {
        if (String(item.title).indexOf(String(inputeds.value)) > -1) {
            return item;
        }
    });
    
    currentPage.value = 1
}

// 日期范围搜索
const data_filters = () => {
    let end_time
    let start_time
    let ars = []
    
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }
    
    // 根据日期范围筛选
    activeList.value = copyList.value.filter((item) => {
        if (time.value ?
            Date.parse(new Date(`${item.createtime}`)) > end_time &&
            Date.parse(new Date(` ${item.createtime}`)) < start_time : true
        ) {
            return item
        }
        ars.push(item)
    });
}

// 批量删除相关
const shows = ref(false);
const setArr = ref([]);
const multipleTableRef = ref()
const SelectArr = ref([])
const All_Delete = ref([])

// 表格选择变化处理
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    
    // 收集选中项ID
    SelectArr.value.forEach(item => {
        All_Delete.value.push(item.id)
    })
    
    console.log(All_Delete.value);
}

// 批量删除操作
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的数据',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}

// 确认批量删除
const deleteid_t = () => {
    typeDel({
        ids: st.value.join(','),
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}
</script>

<style>
/* 样式定义 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

/* 提取的内联样式 */
.box-padding {
    padding: 10px;
}

.search-title {
    width: 220px;
}

.time-title {
    margin-left: 190px;
}

.search-input {
    width: 220px;
}

.search-input-margin {
    margin-left: 20px;
}

.date-picker-container {
    margin-left: 20px;
}

.date-picker {
    width: 220px;
}

.button-group {
    display: flex;
    gap: 10px;
    margin-top: 15px;
}

.export-button {
    height: 35px;
}

.status-buttons {
    display: flex;
    gap: 10px;
    margin-left: 25px;
}

.status-button {
    height: 35px;
}

.data-table {
    width: 100%;
    text-align: center;
}

.status-pending {
    color: rgba(255, 165, 0, 1);
}

.status-completed {
    color: #E3E1E2;
}

.action-approved {
    color: #6BC440;
}

.action-pending {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

.dialog-message {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-buttons {
    display: flex;
    justify-content: end;
}

.form-container {
    padding: 10px;
}

.form-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: 80vh;
}

.form-title {
    padding: 10px;
}

.divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-content {
    margin-top: 20px;
}

.form-width {
    width: 40%;
}

.full-width {
    width: 100%;
}

.dialog-footer {
    position: absolute;
    bottom: 20px;
    right: 40px;
}
</style>